/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;
import entity.Alpha;
import entity.Rect;
import entity.Hat;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import game.Game;
import game.RotateHat;
/**   
 * 
 * @author Đức Trung
 */

public final class PanelMain extends JPanel implements Runnable,ChangeListener,MouseMotionListener,MouseListener {  
 
        public PanelMain() {
        alpha = new Alpha();
        hat = new Hat(513,513);       
        r= new RotateHat(false,21,0);
        play = new Game(r,3,3);      
        update =new Thread(r);
        view = new Thread(this);
        update.start();        
        view.start(); 
        System.out.println("Bắt đầu chơi: ");
        init();
        loadImage();
    }
  
   public void init(){
        DrawBar();
        TextField();
        Slider();
        LaBel();
    }
    /**
     * Xây dựng các TextField hiển thị đáp án
     */
    public void TextField(){
        jt = new JTextField[8];
        for(int i=0;i<8;i++){
        jt[i]= new JTextField();
     //   add(jt[i]);
        jt[i].setBounds(250+40*i,100,40,40);
        jt[i].setEnabled(false);
        }
    }
    /**
     * Xây dựng thanh lực quay nón
     */
    public void Slider(){
        slider = new JSlider();
        slider.setOrientation(SwingConstants.VERTICAL);
        slider.setForeground(Color.white);
	slider.setBounds(900,200, 32, 200);
        slider.setMaximum(35);
        slider.setMinimum(15);
        add(slider);
        slider.addChangeListener(this);
    }
    /**
     * Khởi tạo 29 button đáp án 
     */

    /**
     * 
     */
    public void LaBel(){
     
        bt= new JLabel[29];
        for(int i=0;i<29;i++){
        bt[i]= new JLabel(Button[i].getText());
        bt[i].setFont(new Font("Minion Pro", Font.BOLD, 25)); 
        bt[i].setForeground(Color.white);
        bt[i].setBounds(Button[i].getX()+10,Button[i].getY(),Button[i].getWeight(),Button[i].getHeight());
        add(bt[i]);
        }
        round = new JLabel();
        round.setFont(new Font("Minion Pro", Font.BOLD, 25)); 
        round.setBounds(100, 100,200,200);
        add(round);
        
    }
    /**
     * Vẽ ảnh cái nón
     * @param g 
     */
    public void drawButton(){
       
    }
  
    
    public void DrawBar(){
        int j=0;
        Button = new Rect[29];
        for(int i=0;i<29;i++){     
                
            Button[i]= new Rect(alpha.arrayAlpha(i),700+45*(i-j*6),200+45*j,45,45,false,false);
            if((float)((i+1)%6)==0){
                 j++;
            }    
        }
      
    }
    public void run() {
        
      
         while(true){   
            try {
                repaint();
                view.sleep(1000/20);
            } catch (InterruptedException ex) {
                Logger.getLogger(PanelMain.class.getName()).log(Level.SEVERE, null, ex);
            }
            
         }    
        
    }
      public void paintComponent(Graphics g){
       
        g.clearRect(0,0,1024,700);  
        g.drawImage(img[1],0,0,this);
        g.drawImage(img[3],50,40,300,60, this);
        g.drawImage(img[4],350,40,300,60, this);
        g.drawImage(img[5],650,40,300,60, this);
        t=RotateImage(img[2]);
        g.drawImage(t,250,350,t.getWidth(),t.getHeight(), this);
        g.drawImage(img[6],0,550,1024,150,this);
        for(int i=0;i<29;i++){
       if(Button[i].isClick())
        g.drawImage(img[12],Button[i].getX(),Button[i].getY(),Button[i].getWeight(),Button[i].getHeight(),this);
        else
        g.drawImage(img[11],Button[i].getX(),Button[i].getY(),Button[i].getWeight(),Button[i].getHeight(),this);    
        }
        g.setFont(new Font("Minion Pro", Font.BOLD, 25)); 
        g.setColor(Color.white);
        g.drawString(play.getPlayerCurrent().getName(),250,580);
        g.drawString(new Integer(play.getPlayerCurrent().getTurn()).toString(),400 ,580);
        DrawPlayer(g); 
        g.drawString ("Vòng "+ play.getCurrenRound().getNameRound(),50,580);
        
      }  
  public static BufferedImage[] splitImage(BufferedImage img, int cols, int rows) {
		int w = img.getWidth()/cols-3;
		int h = img.getHeight()/rows;
		int num = 0;
		BufferedImage imgs[] = new BufferedImage[w*h];
		for(int y = 0; y < rows; y++) {
			for(int x = 0; x < cols; x++) {
				imgs[num] = new BufferedImage(w, h, img.getType());
				// Tell the graphics to draw only one block of the image
				Graphics2D g = imgs[num].createGraphics();
				g.drawImage(img,0,0, w, h, w*x, h*y, w*x+w, h*y+h, null);
				g.dispose();
				num++;
			}
		}
		return imgs;
	}
    public void DrawPlayer(Graphics g){
       for(int i=0;i<3;i++){       
        g.drawString(play.getNplayer()[i].getName(),150+300*i,60);
        g.drawString(play.getNplayer()[i].getScore()+"$",170+300*i, 90);
        }
    }
    /**
     * 
     * @param bi Ảnh cần quay 
     * @return  Ảnh mới sau khi quay được một góc angle 
     */
    public BufferedImage RotateImage(BufferedImage bi){
        int w=bi.getWidth();
        int h=bi.getHeight();
        BufferedImage biImage=new BufferedImage(w,h, bi.getType());
        Graphics2D g=biImage.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.rotate(Math.toRadians(r.getAngle()),w/2, h/2);
        g.drawImage(bi,null,0,0);
        bi=biImage;
        return bi;        
    }     

    public void stateChanged(ChangeEvent e) {
        if(slider.getValueIsAdjusting()){
			return;
	}
            play.setClick(false);
          
           if(!r.isNext()){
           if(this.isClick==0)
         {  
            r.setA(slider.getValue());
            r.setStatus(r.GetStatus(r.getAngle(),r.getA())); 
            r.setRun(true);
            this.isClick=1;
            System.out.println(slider.getValue());
         }else{
             if(r.getX()<0){                
              r.setA(slider.getValue());
             r.setX(0);
             r.setMax(0);
             r.setAngle(r.getTotal());
             r.setRun(true);
             r.setStatus(r.GetStatus(r.getAngle(),r.getA()) );
             } 
              System.out.println(slider.getValue());
            }
           }
        }

    public void mouseDragged(MouseEvent e) {
      
    }

    public void mouseMoved(MouseEvent e) {
         for(int i=0;i<29;i++){
               if(Button[i].Contain(e.getX(),e.getY())){
       //            System.out.println(i);
               }
         
       }
    }
    public void mouseClicked(MouseEvent e) {
      for(int i=0;i<29;i++){
                if(Button[i].Contain(e.getX(),e.getY())&&!Button[i].isClick()&&r.isNext()&&play.isIsAnswer()){
                
                       
                }
         
       }
    }
    public void mousePressed(MouseEvent e) {
         for(int i=0;i<29;i++){
                if(Button[i].Contain(e.getX(),e.getY())&&!Button[i].isClick()&&r.isNext()&&play.isIsAnswer()){
                alpha.setAnswer(Button[i].getText());
                play.arraySelect[i]=0;
                play.getPlayer().setAnswer(Button[i].getText());
                System.out.println(Button[i].getText());                   
                Button[i].setClick(true);
                play.setNext(true);
                r.setNext(false);   
                    }
                }
    }

    public void mouseReleased(MouseEvent e) {
       
    }

    public void mouseEntered(MouseEvent e) {
      
    }

    public void mouseExited(MouseEvent e) {
       
    }
    public void loadImage(){
      
      img = new BufferedImage[14];
      for(int i=0;i<14;i++){
            img[i]=this.loadImage("img"+(i)+".png");
      }   
    } 
       public static BufferedImage loadImage(String ref) {  
            BufferedImage bimg = null;  
            try {  

                bimg = ImageIO.read(new File(ref));  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
             return bimg;  
        }  
    
        public BufferedImage[] img;
        public BufferedImage[] abc2;
        public int fps =1000;
        public Thread view;
        public Thread game;
        public Thread update;
        public BufferedImage t;      
        private int isClick=0;
        private Hat hat;
        private RotateHat r;    
        private JTextField[]  jt;
        private JButton[]  jb;
        private Alpha alpha;
        private JButton j;
        private Game play;
        private  JSlider slider;
        private JLabel[] bt ;
        private Rect[] Button;
        private JLabel round ;
        
    }


